package com.hengyue.quartz.service.impl;

import com.hengyue.common.constants.ScheduleConstants;
import com.hengyue.quartz.common.util.job.TaskException;
import com.hengyue.exception.ServiceException;
import com.hengyue.quartz.common.util.ScheduleUtils;
import com.hengyue.quartz.domain.SysJob;
import com.hengyue.quartz.repository.SysJobRepository;
import com.hengyue.quartz.service.ISysJobService;
import jakarta.annotation.PostConstruct;
import jakarta.persistence.criteria.Predicate;
import lombok.RequiredArgsConstructor;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@RequiredArgsConstructor
public class SysJobServiceImpl implements ISysJobService {

    private final SysJobRepository sysJobRepository;

    private final Scheduler scheduler;



    /**
     * 项目启动时，初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException
    {
        scheduler.clear();
        List<SysJob> jobList = sysJobRepository.findAll();
        for (SysJob job : jobList)
        {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }
    /**
     * 获取quartz调度器的计划任务
     *
     * @param job 调度信息
     * @return 调度任务集合
     */
    @Override
    public Page<SysJob> selectJobList(SysJob job, Pageable pageable) {
        Specification<SysJob> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (StringUtils.hasText(job.getJobName())) {
                predicates.add(cb.like(root.get("jobName"), "%" + job.getJobName() + "%"));
            }
            if (StringUtils.hasText(job.getJobGroup())) {
                predicates.add(cb.equal(root.get("jobGroup"), job.getJobGroup()));
            }
            if (StringUtils.hasText(job.getStatus())) {
                predicates.add(cb.equal(root.get("status"), job.getStatus()));
            }
            if (StringUtils.hasText(job.getInvokeTarget())) {
                predicates.add(cb.like(root.get("invokeTarget"), "%" + job.getInvokeTarget() + "%"));
            }

            return cb.and(predicates.toArray(new Predicate[0]));
        };

        return sysJobRepository.findAll(spec, pageable);
    }

    /**
     * 通过调度任务ID查询调度信息
     *
     * @param jobId 调度任务ID
     * @return 调度任务对象信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysJob selectJobById(Long jobId) {

        return sysJobRepository.findById(jobId)
                .orElseThrow(() -> new ServiceException("任务不存在"));

    }

    /**
     * @param job
     * @return
     */
    @Override
    public List<SysJob> selectJobAll(SysJob job) {
        return sysJobRepository.findAll();
    }

    @Override
    @Transactional
    public void changeStatus(SysJob job) throws SchedulerException {

        if (job == null || job.getId() == null || job.getStatus() == null) {
            throw new ServiceException("任务参数不能为空");
        }
        SysJob newJob = selectJobById(job.getId());
        newJob.setStatus(job.getStatus());
        sysJobRepository.save(newJob);
        String status = job.getStatus();
        if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
            scheduler.resumeJob(ScheduleUtils.getJobKey(newJob.getId(), newJob.getJobGroup()));
        } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
            scheduler.resumeJob(ScheduleUtils.getJobKey(newJob.getId(), newJob.getJobGroup()));
        }
    }



    /**
     * 批量删除调度信息
     *
     * @param jobIds 需要删除的任务ID
     * @return 结果
     */
    @Override
    @Transactional
    public void deleteJobByIds(Long[] jobIds) throws SchedulerException {
        // 先删除 Quartz 任务
        for (Long jobId : jobIds) {
            SysJob job = selectJobById(jobId);
            scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, job.getJobGroup()));
        }
        // 再批量删除数据库记录
        sysJobRepository.deleteAllByIdInBatch(Arrays.asList(jobIds));
    }

    /**
     * 任务调度状态修改
     *
     * @param job 调度信息
     * @return 结果
     */


    /**
     * 立即运行任务
     *
     * @param job 调度信息
     * @return 结果
     */
    @Override
    public boolean run(SysJob job) throws SchedulerException {

        boolean result = false;
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup();
        SysJob properties = selectJobById(job.getId());
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            result = true;
            scheduler.triggerJob(jobKey, dataMap);
        }
        return result;

    }

    /**
     * 新增任务
     *
     * @param job 调度信息
     * @return 结果
     */
    @Override
    public void insertJob(SysJob job) throws SchedulerException, TaskException {
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        sysJobRepository.save(job);
    }


    /**
     * 更新任务
     *
     * @param job 调度信息
     * @return 结果
     */
    @Override
    public void updateJob(SysJob job) throws SchedulerException, TaskException {
        sysJobRepository.save(job);
        updateSchedulerJob(job, job.getJobGroup());
    }

    /**
     * 校验cron表达式是否有效
     *
     * @param cronExpression 表达式
     * @return 结果
     */
    @Override
    public boolean checkCronExpressionIsValid(String cronExpression) {
        return false;
    }

    /**
     * 更新任务
     *
     * @param job      任务对象
     * @param jobGroup 任务组名
     */
    public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException {
        Long jobId = job.getId();
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }
}
